package com.muyu.cloud.commodity.service.imp;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.muyu.cloud.commodity.domain.model.*;
import com.muyu.cloud.commodity.domain.req.ProductReq;
import com.muyu.cloud.commodity.domain.req.ProductAddNewReq;
import com.muyu.cloud.commodity.domain.req.ProductSkuAddNewReq;
import com.muyu.cloud.commodity.enums.ProductEnumes;
import com.muyu.cloud.commodity.info.SpecGroupInfo;
import com.muyu.cloud.commodity.info.SpecValueInfo;
import com.muyu.cloud.commodity.mapper.ProductCommentMapper;
import com.muyu.cloud.commodity.mapper.ProductMapper;
import com.muyu.cloud.commodity.mapper.ProductSkuMapper;
import com.muyu.cloud.commodity.mapper.ProductSkuSpecMapper;
import com.muyu.cloud.commodity.domain.model.*;
import com.muyu.cloud.commodity.domain.resp.ProductDetailResp;
import com.muyu.cloud.commodity.domain.resp.ProductSkuDetailResp;
import com.muyu.cloud.commodity.domain.resp.ProductVo;
import com.muyu.cloud.commodity.service.ProductService;
import com.muyu.cloud.commodity.domain.req.ProductCommentListReq;
import com.muyu.cloud.commodity.domain.resp.ProductCommentListResp;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.core.web.page.DataPageResp;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:602048165@qq.com">60204</a>
 * @version 1.0
 * @description:
 * @date 2025/9/14 19:36
 */
@Service
public class ProductServiceImp implements ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private ProductSkuSpecMapper productSkuSpecMapper;
    @Autowired
    private ProductCommentMapper productCommentMapper;

    /**
     * 获取商品列表
     *
     * @param productReq
     * @return
     */
    @Override
    public DataPageResp<ProductVo> pageQuery(ProductReq productReq) {
        //1.查询总记录数
        Integer total= productMapper.countByPage(productReq);
        
        //2.计算偏移量
        if (productReq.getPageNum() != null && productReq.getPageSize() != null) {
            productReq.setOffset((productReq.getPageNum() - 1) * productReq.getPageSize());
        }
        
        //3.查询分页数据
        List<ProductVo>productVoList= productMapper.selectByPage(productReq);
        
        //4.封装返回结果
        DataPageResp<ProductVo> pageResp = new DataPageResp<>();
        pageResp.setRows(productVoList);
        pageResp.setTotal(total);
        return pageResp;
    }

    /**
     * 商品详情
     * @param id
     * @return
     */
    @Override
    public ProductDetailResp getDetilById(Long id) {
        //商品基本信息
        Product product = productMapper.selectDetailById(id);
        if (product==null){
            throw new RuntimeException("商品不存在");
        }
        //2.获取sku列表与规格值
        List<ProductSku> skuList = productSkuMapper.selectByProductId(id);
        List<ProductSkuDetailResp> skuDetailList = skuList.stream()
                .map(this::buildSkuDetailResp)
                .toList();
        // 3. 获取评价统计
            //获取该商品的平均评分
        BigDecimal avgScore = productCommentMapper.selectAvgScoreByProductId(id);
            //获取评价数量
        Integer commentCount = productCommentMapper.countByProductId(id);

        // 4. 获取规格组信息（用于前端规格选择）
        List<SpecGroupInfo> specGroups = getSpecGroupsByProductId(id);

        // 5. 构建响应对象
        return ProductDetailResp.builder()
                .id(product.getId())
                .productName(product.getProductName())
                .productPic(product.getProductPic())
                .description(product.getDescription())
                .marketPrice(product.getMarketPrice())
                .categoryId(product.getCategoryId())
                .brandId(product.getBrandId())
                .viewCount(product.getViewCount())
                .collectCount(product.getCollectCount())
                .status(product.getStatus())
                .createdAt(product.getCreatedAt())
                .updatedAt(product.getUpdatedAt())
                .categoryName(product.getCategoryName())
                .brandName(product.getBrandName())
                .skuList(skuDetailList)
                .avgScore(avgScore)
                .commentCount(commentCount)
                .specGroups(specGroups)
                .build();
    }

    private List<SpecGroupInfo> getSpecGroupsByProductId(Long id) {
        //1.获取该商品涉及的所有规格组
        List<SpecGroupInfo> specGroups = productSkuSpecMapper.selectSpecGroupsByProductId(id);

        // 2. 为每个规格组填充规格值列表
        for (SpecGroupInfo specGroup : specGroups) {
            List<SpecValueInfo> specValues = productSkuSpecMapper.selectSpecValuesByGroupId(specGroup.getGroupId());
            specGroup.setSpecValues(specValues);
        }

        return specGroups;
    }

    private ProductSkuDetailResp buildSkuDetailResp(ProductSku sku) {
        // 获取该SKU的规格值名称
        List<String> specValues = productSkuSpecMapper.selectSpecValueNamesBySkuId(sku.getId());
        // 追加：同时查询规格值ID，便于前端回显
        List<Long> specValueIds = productSkuSpecMapper.selectSpecValueIdsBySkuId(sku.getId());

        return ProductSkuDetailResp.builder()
                .id(sku.getId())
                .skuCode(sku.getSkuCode())
                .salePrice(sku.getSalePrice())
                .costPrice(sku.getCostPrice())
                .stock(sku.getStock())
                .sales(sku.getSales())
                .image(sku.getImage())
                .status(sku.getStatus())
                .specValues(specValues)
                .specValueIds(specValueIds)
                .build();
    }

    /**
     * 修改商品
     * @param productUpdateModel
     */
    @Override
    @Transactional
    public void upddateProduct(ProductUpdateModel productUpdateModel) {
        Long productId = productUpdateModel.getId();
        //1.验证商品是否存在
        Product existingProduct= productMapper.selectById(productId);
        if (existingProduct==null){
            throw new RuntimeException("商品不存在");
        }

        //2.验证sku编码唯一性
        List<ProductSkuUpdateModel> skuList = productUpdateModel.getSkuList();
        List<String>skuCodes= skuList.stream().map(ProductSkuUpdateModel::getSkuCode).toList();
        //检查是否重复的sku编码
        long distinctCount = skuCodes.stream().distinct().count();
        if (distinctCount!=skuCodes.size()){
            throw new RuntimeException("sku编码不能重复");
        }
        //查询数据库是否已存在
        List<String> existingCodes=productSkuMapper.selectExistingSkuCodesExcludeProduct(skuCodes,productId);
        if (!CollectionUtils.isNotEmpty(existingCodes)){
            throw new RuntimeException("SKU编码已存在: "+existingCodes);
        }
        //3.验证规格值有效性
        //所有规格值
        List<Long>specValueIds = skuList.stream().flatMap(sku -> sku.getSpecValueIds().stream()).distinct().toList();
        //验证规格值是否存在且有效
        List<Long>validSpecValueIds= productSkuSpecMapper.selectValidSpecValueIds(specValueIds);
        if (validSpecValueIds.size()!=specValueIds.size()){
            throw new RuntimeException("存在无效的规格id");
        }
        //4.更新商品基本信息
        Product product = new Product();
        BeanUtils.copyProperties(productUpdateModel,product);
        productMapper.updateById(product);
        //5.处理sku更新
        //获取当前商品的所有sku Id
        List<Long>currentSkuIds=productMapper.selectSkuIdsByProductId(productId);
        //获取请求中的sku id
        productUpdateModel.getSkuList().stream().filter(sku->!sku.getIsNew()&&sku.getId()!=null).map(ProductSkuUpdateModel::getId).toList();
        //删除不需要的sku
        List<Long> skuIdsToDelete = currentSkuIds.stream()
                .filter(id -> !currentSkuIds.contains(id))
                .toList();
        if (!CollectionUtils.isEmpty(skuIdsToDelete)){
            //删除sku与规格值的关联
            productMapper.deleteBySkuIds(skuIdsToDelete);
            //删除sku
            productMapper.deleteByIds(skuIdsToDelete);
        }
        for (ProductSkuUpdateModel skuUpdate :productUpdateModel.getSkuList()){
            if (skuUpdate.getIsNew()){
                //新增sku
                ProductSku productSku = new ProductSku();
                BeanUtils.copyProperties(skuUpdate,productSku);
                productSkuMapper.insert(productSku);
                //添加sku与规格关联
                List<ProductSkuSpec>skuSpecList= skuUpdate.getSpecValueIds().stream().map(specValueId->{
                    ProductSkuSpec skuSpec = new ProductSkuSpec();
                    skuSpec.setSkuId(productSku.getId());
                    skuSpec.setSpecValueId(specValueId);
                    skuSpec.setCreatedAt(LocalDateTime.now());
                    return skuSpec;
                }).toList();
                if (!CollectionUtils.isEmpty(skuSpecList)){
                    productSkuSpecMapper.batchInsert(skuSpecList);
                }
            }else {
                //修改更新sku基本信息
                ProductSku productSku = new ProductSku();
                BeanUtils.copyProperties(skuUpdate,productSku);
                productSkuMapper.updateById(productSku);
                //先删除旧的sku与规格的关联再插入新的关联关系
          //先删除
                productSkuSpecMapper.deleteBySkuId(skuUpdate.getId());
                //后添加
                List<ProductSkuSpec> skuSpecList = skuUpdate.getSpecValueIds().stream()
                        .map(specValueId -> {
                            ProductSkuSpec skuSpec = new ProductSkuSpec();
                            skuSpec.setSkuId(skuUpdate.getId());
                            skuSpec.setSpecValueId(specValueId);
                            skuSpec.setCreatedAt(LocalDateTime.now());
                            return skuSpec;
                        })
                        .toList();

                if (!CollectionUtils.isEmpty(skuSpecList)) {
                    productSkuSpecMapper.batchInsert(skuSpecList);
                }
            }
        }

    }

    /**
     * 商品添加
     * @param req
     */
    @Override
    @Transactional
    public void addProduct(ProductAddNewReq req) {
        // 1. 验证规格值ID的有效性
        List<Long> validSpecValueIds = productSkuSpecMapper.selectValidSpecValueIds(req.getSpecValueIds());
        if (validSpecValueIds.size() != req.getSpecValueIds().size()) {
            throw new RuntimeException("存在无效的规格值ID");
        }

        // 2. 添加商品基本信息
        Product product = new Product();
        product.setProductName(req.getProductName());
        product.setProductPic(req.getProductPic());
        product.setDescription(req.getDescription());
        product.setMarketPrice(req.getMarketPrice());
        product.setCategoryId(req.getCategoryId());
        product.setBrandId(req.getBrandId());
        product.setStatus(req.getStatus());
        product.setViewCount(ProductEnumes.ZERO.getCode());
        product.setCollectCount(ProductEnumes.Collect.getCode());
        product.setIsDeleted(ProductEnumes.DEL2.getCode());

        int productResult = productMapper.insertReturnId(product);
        if (productResult == 0) {
            throw new RuntimeException("商品添加失败");
        }
        Long productId = product.getId();

        // 3. 添加SKU信息
        List<ProductSku> skuList = new ArrayList<>();
        List<ProductSkuSpec> skuSpecList = new ArrayList<>();

        for (ProductSkuAddNewReq skuReq : req.getSkuList()) {
            // 生成SKU编码（如果未提供）
            String skuCode = skuReq.getSkuCode();
            if (skuCode == null || skuCode.trim().isEmpty()) {
                skuCode = generateSkuCode(productId, skuReq.getSpecValueIds());
            }

            // 创建SKU
            ProductSku sku = new ProductSku();
            sku.setProductId(productId);
            sku.setSkuCode(skuCode);
            sku.setSalePrice(skuReq.getSalePrice());
            sku.setCostPrice(skuReq.getCostPrice());
            sku.setStock(skuReq.getStock());
            sku.setSales(0);
            sku.setImage(skuReq.getImage());
            sku.setStatus(skuReq.getStatus());

            int skuResult = productSkuMapper.insertReturnId(sku);
            if (skuResult == 0) {
                throw new RuntimeException("SKU添加失败");
            }
            Long skuId = sku.getId();
            skuList.add(sku);

            // 4. 添加SKU与规格值的关联关系
            if (skuReq.getSpecValueIds() != null && !skuReq.getSpecValueIds().isEmpty()) {
                for (Long specValueId : skuReq.getSpecValueIds()) {
                    ProductSkuSpec skuSpec = new ProductSkuSpec();
                    skuSpec.setSkuId(skuId);
                    skuSpec.setSpecValueId(specValueId);
                    skuSpecList.add(skuSpec);
                }
            }
        }

        // 5. 批量插入SKU与规格值关联关系
        if (!skuSpecList.isEmpty()) {
            productSkuSpecMapper.batchInsert(skuSpecList);
        }
    }

    /**
     * 生成SKU编码
     * 格式：商品ID + 规格值ID组合
     */
    private String generateSkuCode(Long productId, List<Long> specValueIds) {
        StringBuilder sb = new StringBuilder();
        sb.append("SKU").append(productId);
        if (specValueIds != null && !specValueIds.isEmpty()) {
            for (Long specValueId : specValueIds) {
                sb.append("_").append(specValueId);
            }
        }
        return sb.toString();
    }

    /**
     * 上架
     * @param id
     */
    @Override
    public void upProduct(Long id) {
        int rows = productMapper.updateStatusById(id, 1);
        if (rows == 0) {
            throw new RuntimeException("上架失败，商品不存在");
        }
    }

    /**
     * 下架
     * @param id
     */
    @Override
    public void downProduct(Long id) {
        int rows = productMapper.updateStatusById(id, 0);
        if (rows == 0) {
            throw new RuntimeException("下架失败，商品不存在");
        }
    }

    /**
     * 商品评价列表
     * @param req
     * @return
     */
    @Override
    public DataPageResp<ProductCommentListResp> pageComments(ProductCommentListReq req) {
        List<ProductCommentListResp> rows = productCommentMapper.selectPageByQuery(req);
        // 这里统计总数
        DataPageResp<ProductCommentListResp> page = new DataPageResp<>();
        page.setRows(rows);
        // 估算总数
        Integer total = productCommentMapper.countByProductId(req.getProductId());
        page.setTotal(total == null ? 0 : total);
        return page;
    }

    /**
     * 评论审核通过
     * @param ids
     */
    @Override
    public void approveComments(List<Long> ids) {
        if (ids == null || ids.isEmpty()) return;
        productCommentMapper.updateStatusByIds(ids, 1);
    }

    /**
     * 评论审核驳回
     * @param ids
     */
    @Override
    public void rejectComments(List<Long> ids) {
        if (ids == null || ids.isEmpty()) return;
        productCommentMapper.updateStatusByIds(ids, 2);
    }
}